﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace Medianamik.Globalization.Utilities
{
    /// <summary>
    /// This class can be used to export selected resource sets as a series of SQL queries.
    /// The file can then be applied as a patch.
    /// </summary>
    public class SqlResourceExporter : ResourceExporter<StringBuilder>
    {
        protected override StringBuilder CreateInstance()
        {
            return new StringBuilder();
        }

        protected override void AddResource(StringBuilder export, Resource resource)
        {
            var formattedValue = resource.Value.Replace("'", "''");

            export.AppendFormat(
                "IF (NOT EXISTS(SELECT 1 FROM Localizations WHERE ResourceId = '{0}' AND LocaleId = '{1}' AND ResourceSet = '{2}'))",
                resource.Id, resource.CultureName, resource.ResourceSet);
            export.AppendLine();
            export.AppendFormat(
                "\tINSERT INTO Localizations(ResourceId, Value, LocaleId, ResourceSet) VALUES('{0}', '{1}', '{2}', '{3}')",
                resource.Id, formattedValue, resource.CultureName, resource.ResourceSet);
            export.AppendLine();
            export.AppendLine("ELSE");
            export.AppendFormat(
                "\tUPDATE Localizations SET Value = '{1}' WHERE ResourceId = '{0}' AND LocaleId = '{2}' AND ResourceSet = '{3}'\n",
                resource.Id, formattedValue, resource.CultureName, resource.ResourceSet);
            
            export.Append("go\n");
            
        }
    }
}